<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

/*分销*/
namespace app\controller;
use think\facade\Db;
class ApiAgent extends ApiCommon
{
	public function initialize(){
		parent::initialize();
		$this->checklogin();
	}
	public function commissionSurvey(){
		$userinfo = Db::name('member')->field('id,headimg,nickname,pid,commission,totalcommission')->where('aid',aid)->where('id',mid)->find();
		$count = 0 + Db::name('member_commission_withdrawlog')->where('aid',aid)->where('mid',mid)->sum('txmoney');
		$count0 = 0 + Db::name('member_commission_withdrawlog')->where('aid',aid)->where('mid',mid)->where('status',0)->sum('txmoney');
		$count1 = 0 + Db::name('member_commission_withdrawlog')->where('aid',aid)->where('mid',mid)->where('status',1)->sum('txmoney');
		$count2 = 0 + Db::name('member_commission_withdrawlog')->where('aid',aid)->where('mid',mid)->where('status',2)->sum('txmoney');
		$count3 = 0 + Db::name('member_commission_withdrawlog')->where('aid',aid)->where('mid',mid)->where('status',3)->sum('txmoney');
		if($userinfo){
			$countdqr1 = Db::query("select sum(parent1commission)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2) and og.parent1={$userinfo['id']}");
			$countdqr2 = Db::query("select sum(parent2commission)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2) and og.parent2={$userinfo['id']}");
			$countdqr3 = Db::query("select sum(parent3commission)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2) and og.parent3={$userinfo['id']}");
		}
		if($userinfo['pid']){
			$userinfo['pnickname'] = Db::name('member')->where('aid',aid)->where('id',$userinfo['pid'])->value('nickname');
		}
		$countdqr = 0 + $countdqr1[0]['c'] + $countdqr2[0]['c'] + $countdqr3[0]['c'];
		
		$count = number_format($count,2,'.','');
		$count0 = number_format($count0,2,'.','');
		$count1 = number_format($count1,2,'.','');
		$count2 = number_format($count2,2,'.','');
		$count3 = number_format($count3,2,'.','');
		$countdqr = number_format($countdqr,2,'.','');

		$set = Db::name('admin_set')->where('aid',aid)->find();

		//是否显示分红订单
		$levelinfo = Db::name('member_level')->where('id',$this->member['levelid'])->find();
		$levelRecord = Db::name('member_level_record')->where('mid',mid)->select();
        $levelids = $levelRecord->column('levelid');
        $levelExtend = Db::name('member_level')->whereIn('id',$levelids);
		$showfenhong = false;
		$hasfenhong = false;
		$hasteamfenhong = false;
		$hasareafenhong = false;
        $hasYeji = false;
		if($levelinfo['fenhong'] > 0){ //有股东分红
            $showfenhong = true;
			$hasfenhong = true;
		}
        if($levelExtend->where('fenhong', '>', 0)->count()) {
            $showfenhong = true;
			$hasfenhong = true;
        }
		if($levelinfo['teamfenhonglv'] > 0 && ($levelinfo['teamfenhongbl'] > 0 || $levelinfo['teamfenhong_money'] > 0)){ //有团队分红
			$showfenhong = true;
			$hasteamfenhong = true;
		}
        if($levelinfo['product_teamfenhong_ids'] != '' && $levelinfo['product_teamfenhonglv'] > 0 && ($levelinfo['product_teamfenhong_money'] > 0)){ //有商品团队分红
            $showfenhong = true;
            $hasteamfenhong = true;
        }
        if(!empty($levelinfo['level_teamfenhong_ids']) && $levelinfo['level_teamfenhonglv'] > 0 && ($levelinfo['level_teamfenhongbl'] > 0 || $levelinfo['level_teamfenhong_money'] > 0)){ //有等级团队分红
            $showfenhong = true;
            $hasteamfenhong = true;
        }
        if(!empty($levelinfo['tongji_yeji']) && $levelinfo['tongji_yeji'] == 1) {
            $hasYeji = true;
        }
		$countfenhong = $levelExtend->where('teamfenhonglv', '>', 0)->where(function ($query) {
            $query->where('teamfenhongbl','>',0)->whereOr('teamfenhong_money','>',0);
        })->count();
        if($countfenhong) {
            $showfenhong = true;
			$hasteamfenhong = true;
        }
		if($levelinfo['areafenhong'] > 0 && $levelinfo['areafenhongbl'] > 0){ //有区域代理分红
			$showfenhong = true;
			$hasareafenhong = true;
		}
        if($levelExtend->where('areafenhong', '>', 0)->where('areafenhongbl', '>', 0)->count()) {
            $showfenhong = true;
			$hasareafenhong = true;
        }
		if($this->member['areafenhong'] > 0 && $this->member['areafenhongbl'] > 0){ //有单独设置的区域代理分红
			$showfenhong = true;
			$hasareafenhong = true;
		}
        if($levelRecord->where('areafenhong', '>', 0)->where('areafenhongbl', '>', 0)->count()) {
            $showfenhong = true;
			$hasareafenhong = true;
        }
        //预计佣金
//		$commissionyj1 = Db::query("select sum(parent1commission)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2 or o.status=3) and iscommission=0 and og.parent1=".mid."");
//		$commissionyj2 = Db::query("select sum(parent2commission)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2 or o.status=3) and iscommission=0 and og.parent2=".mid."");
//		$commissionyj3 = Db::query("select sum(parent3commission)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2 or o.status=3) and iscommission=0 and og.parent3=".mid."");
		$commissionyj_collage1 = Db::name('collage_order')->where('aid',aid)->where('parent1',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent1commission');
        $commissionyj_collage2 = Db::name('collage_order')->where('aid',aid)->where('parent2',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent2commission');
        $commissionyj_collage3 = Db::name('collage_order')->where('aid',aid)->where('parent3',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent3commission');
        $commissionyj_score1 = Db::name('scoreshop_order_goods')->where('aid',aid)->where('parent1',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent1commission');
        $commissionyj_score2 = Db::name('scoreshop_order_goods')->where('aid',aid)->where('parent2',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent2commission');
        $commissionyj_score3 = Db::name('scoreshop_order_goods')->where('aid',aid)->where('parent3',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent3commission');
        //ddwx_seckill_order 不存在iscommission字段
        $commissionyj_yuyue1 = Db::name('yuyue_order')->where('aid',aid)->where('parent1',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent1commission');
        $commissionyj_yuyue2 = Db::name('yuyue_order')->where('aid',aid)->where('parent2',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent2commission');
        $commissionyj_yuyue3 = Db::name('yuyue_order')->where('aid',aid)->where('parent3',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent3commission');
        $commissionyj_ke1 = Db::name('kecheng_order')->where('aid',aid)->where('parent1',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent1commission');
        $commissionyj_ke2 = Db::name('kecheng_order')->where('aid',aid)->where('parent2',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent2commission');
        $commissionyj_ke3 = Db::name('kecheng_order')->where('aid',aid)->where('parent3',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent3commission');
        $commissionyj_tuan1 = Db::name('tuangou_order')->where('aid',aid)->where('parent1',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent1commission');
        $commissionyj_tuan2 = Db::name('tuangou_order')->where('aid',aid)->where('parent2',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent2commission');
        $commissionyj_tuan3 = Db::name('tuangou_order')->where('aid',aid)->where('parent3',mid)->whereIn('status',[1,2,3])->where('iscommission',0)->sum('parent3commission');
        //todo 其他佣金
        $recordyj = Db::name('member_commission_record')->where('aid',aid)->where('mid',mid)->where('type','<>','shop')->where('status',0)->sum('commission');
        $recordyjshop = Db::name('member_commission_record')->alias('r')->leftJoin('shop_order o','r.orderid=o.id')->where('r.aid',aid)->where('r.mid',mid)->where('r.type','shop')->where('r.status',0)->where('o.status','in',[1,2,3])->sum('r.commission');
        $commissionyj = 0 /*+ $commissionyj1[0]['c'] + $commissionyj2[0]['c'] + $commissionyj3[0]['c']*/
            + $commissionyj_collage1 + $commissionyj_collage2 + $commissionyj_collage3
            + $commissionyj_score1 + $commissionyj_score2 + $commissionyj_score3
            + $commissionyj_yuyue1 + $commissionyj_yuyue2 + $commissionyj_yuyue3
            + $commissionyj_ke1 + $commissionyj_ke2 + $commissionyj_ke3
            + $commissionyj_tuan1 + $commissionyj_tuan2 + $commissionyj_tuan3
            + $recordyj + $recordyjshop;
		$userinfo['fenhong'] = Db::name('member_fenhonglog')->where('aid',aid)->where('mid',mid)->where('type','fenhong')->sum('commission');
		$userinfo['areafenhong'] = Db::name('member_fenhonglog')->where('aid',aid)->where('mid',mid)->where('type','areafenhong')->sum('commission');
		$userinfo['teamfenhong'] = Db::name('member_fenhonglog')->where('aid',aid)->where('mid',mid)->where('type','teamfenhong')->sum('commission');

		$userinfo['fenhong'] = round($userinfo['fenhong'],2);
		$userinfo['areafenhong'] = round($userinfo['areafenhong'],2);
		$userinfo['teamfenhong'] = round($userinfo['teamfenhong'],2);
		$userinfo['commission_yj'] = $commissionyj;

		if($showfenhong){
			$rs = \app\common\Fenhong::gdfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$userinfo['fenhong_yj'] = round($rs['commissionyj'],2);
			$userinfo['commission_yj'] += $userinfo['fenhong_yj'];
		}
		if($hasteamfenhong){
			$rs1 = \app\common\Fenhong::teamfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$rs2 = \app\common\Fenhong::product_teamfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$rs3 = \app\common\Fenhong::level_teamfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$teamfenhong_yj = 0;
			if($rs1 && $rs1['oglist']){
				$teamfenhong_yj += $rs1['commissionyj'];
			}
			if($rs2 && $rs2['oglist']){
				$teamfenhong_yj += $rs2['commissionyj'];
			}
			if($rs3 && $rs3['oglist']){
				$teamfenhong_yj += $rs3['commissionyj'];
			}
			$userinfo['teamfenhong_yj'] = round($teamfenhong_yj,2);
			$userinfo['commission_yj'] += $userinfo['teamfenhong_yj'];
		}
		if($hasareafenhong){
			$rs = \app\common\Fenhong::areafenhong(aid,$this->sysset,[],0,time(),1,mid);
			$userinfo['areafenhong_yj'] = round($rs['commissionyj'],2);
			$userinfo['commission_yj'] += $userinfo['areafenhong_yj'];
		}
		$userinfo['commission_yj'] = round($userinfo['commission_yj'],2);

		if($set['teamyeji_show']==1){ //团队业绩
			//总业绩
			//$levelids = Db::name('member_level')->where('aid',aid)->where('sort','<',$levelinfo['sort'])->column('id');
			$levelids = Db::name('member_level')->where('aid',aid)->column('id');
			$yejiwhere = [];
			//$yejiwhere[] = ['isfenhong','=',0];
			//if($set['fhjiesuantime_type'] == 1){
				$yejiwhere[] = ['status','in','1,2,3'];
			//}else{
			//	$yejiwhere[] = ['status','=','3'];
			//}
			$totalyeji = 0;
			$downmids = \app\common\Member::getteammids(aid,mid,999,$levelids);
			//var_dump($downmids);
			$teamyeji = Db::name('shop_order_goods')->where('aid',aid)->where('mid','in',$downmids)->where($yejiwhere)->sum('totalprice');
		}
		if($set['teamnum_show']==1){ //团队总人数
			if($set['teamyeji_show']!=1){
				$downmids = \app\common\Member::getteammids(aid,mid,999,$levelids);
			}
			$teamnum = count($downmids);
		}
		$gongxianfenhong_show = 0;
		if($set['gongxianfenhong_show'] == 1){
			$pergxcommon = 0;
			if($set['partner_gongxian']==1 && $levelinfo['fenhong'] > 0 && $levelinfo['fenhong_gongxian_percent'] > 0){
				$gongxianfenhong_show = 1;

				
				$orderwhere = [];
				$orderwhere[] = ['aid','=',aid];
				$orderwhere[] = ['isfenhong','=',0];
				//if($set['fhjiesuantime_type'] == 1){
				//	$orderwhere[] = ['status','in','1,2,3'];
				//}else{
				//	$orderwhere[] = ['status','=','3'];
				//}
				$orderwhere[] = ['status','in','1,2,3'];
				$real_totalprice = Db::name('shop_order_goods')->where($orderwhere)->sum('real_totalprice');
				if($set['fhjiesuantime_type'] == 0){
					$fenhongprice = $real_totalprice;
				}else{
					$cost_price = Db::name('shop_order_goods')->where($orderwhere)->sum('cost_price');
					$num = Db::name('shop_order_goods')->where($orderwhere)->sum('num');
					$fenhongprice = $real_totalprice - $cost_price * $num;
				}

				$fhlevellist = Db::name('member_level')->where('aid',aid)->where('fenhong','>','0')->order('sort desc,id desc')->column('id,cid,name,fenhong,fenhong_num,fenhong_max_money,sort,fenhong_gongxian_minyeji,fenhong_gongxian_percent','id');
				$lastmidlist = [];
				$total_fenhong_partner = $this->member['total_fenhong_partner'];
				$commission = 0;
				foreach($fhlevellist as $fhlevel){
					$where = [];
					$where[] = ['aid', '=', aid];
					$where[] = ['levelid', '=', $fhlevel['id']];
					$where2 = [];
					$where2[] = ['ml.aid', '=', aid];
					$where2[] = ['ml.levelid', '=', $fhlevel['id']];
					if ($fhlevel['fenhong_max_money'] > 0) {
						$where[] = ['total_fenhong_partner', '<', $fhlevel['fenhong_max_money']];
						$where2[] = ['m.total_fenhong_partner', '<', $fhlevel['fenhong_max_money']];
					}
					if ($defaultCid > 0 && $defaultCid != $fhlevel['cid']) {

					} else {
						if ($fhlevel['fenhong_num'] > 0) {
							$midlist = Db::name('member')->where($where)->order('levelstarttime,id')->limit(intval($fhlevel['fenhong_num']))->column('id,total_fenhong_partner', 'id');
						} else {
							$midlist = Db::name('member')->where($where)->column('id,total_fenhong_partner', 'id');
						}
					}
					
					if($this->sysset['partner_jiaquan'] == 1){
						$oldmidlist = $midlist;
						$midlist = array_merge((array)$lastmidlist,(array)$midlist);
						$lastmidlist = array_merge((array)$lastmidlist,(array)$oldmidlist);
					}

					if (!$midlist) continue;
					
					//股东贡献量分红 开启后可设置一定比例的分红金额按照股东的团队业绩量分红
					$pergxcommon = 0;
					if($this->sysset['partner_gongxian']==1 && $fhlevel['fenhong_gongxian_percent'] > 0){
						$gongxian_percent = $fhlevel['fenhong'] * $fhlevel['fenhong_gongxian_percent']*0.01;
						$fhlevel['fenhong'] = $fhlevel['fenhong'] * (1 - $fhlevel['fenhong_gongxian_percent']*0.01);
						$gongxianCommissionTotal = $gongxian_percent * $fenhongprice * 0.01;
						//总业绩
						//$levelids = Db::name('member_level')->where('aid',aid)->where('sort','<',$fhlevel['sort'])->column('id');
						$levelids = Db::name('member_level')->where('aid',aid)->column('id');
						$yejiwhere = [];
						$yejiwhere[] = ['isfenhong','=',0];
						//if($fhjiesuantime_type == 1) {
							$yejiwhere[] = ['status','in','1,2,3'];
						//}else{
						//	$yejiwhere[] = ['status','=','3'];
						//}
						$totalyeji = 0;
						foreach($midlist as $kk=>$item){
							$downmids = \app\common\Member::getteammids(aid,$item['id'],999,$levelids);
							$yeji = Db::name('shop_order')->where('aid',aid)->where('mid','in',$downmids)->where($yejiwhere)->sum('totalprice');
							$midlist[$kk]['yeji'] = $yeji;
							$totalyeji += $yeji;
						}
						if($totalyeji > 0){
							$pergxcommon = $gongxianCommissionTotal / $totalyeji;
						}else{
							$pergxcommon = 0;
						}
					}

					$fenhongmoney = $fhlevel['fenhong'] * $fenhongprice * 0.01 / count($midlist);//平均分给此等级的会员
					foreach($midlist as $item){
						if($item['id'] == mid){
							$gxcommon = 0;
							if($pergxcommon > 0){
								if($item['yeji'] >= $fhlevel['fenhong_gongxian_minyeji']){
									$gxcommon = $item['yeji'] * $pergxcommon;
								}
							}
							$commission += $gxcommon;
							if ($fhlevel['fenhong_max_money'] > 0) {
								if ($fenhongmoney + $total_fenhong_partner > $fhlevel['fenhong_max_money']) {
									$fenhongmoney = $fhlevel['fenhong_max_money'] - $total_fenhong_partner;
								}
								$total_fenhong_partner += $fenhongmoney;//总分红增加
							}
							//$commission += $fenhongmoney;
							break;
						}
					}
				}

				$gongxianfenhong = $commission;
			}
		}

		//卡片
        $rsset = [];
        $rsset['parent_show'] = $set['parent_show'];
        $rsset['teamfenhong_show'] = $set['teamfenhong_show'];
        $rsset['commissionlog_show'] = $set['commissionlog_show'];
        $rsset['commissionrecord_show'] = $set['commissionrecord_show'];
        $rsset['fhorder_show'] = $set['fhorder_show'];
        $rsset['fhlog_show'] = $set['fhlog_show'];

		$rdata = [];
		$rdata['count'] = $count;
		$rdata['count1'] = $count1;
		$rdata['count2'] = $count2;
		$rdata['count3'] = $count3;
		$rdata['count0'] = $count0;
		$rdata['countdqr'] = $countdqr;
		$rdata['comwithdraw'] = $set['comwithdraw'];
		$rdata['comwithdrawmin'] = $set['comwithdrawmin'];
		$rdata['commission2money'] = $set['commission2money'];
		$rdata['fxjiesuantime'] = $set['fxjiesuantime'];
		$rdata['showfenhong'] = $showfenhong;
		$rdata['hasfenhong'] = $hasfenhong;
		$rdata['hasteamfenhong'] = $hasteamfenhong;
		$rdata['hasareafenhong'] = $hasareafenhong;
        $rdata['showMendianOrder'] = $showMendianOrder;
        $rdata['hasYeji'] = $hasYeji;
        $rdata['teamyeji_show'] = $set['teamyeji_show'];
        $rdata['set'] = $rsset;
		if($rdata['teamyeji_show'] == 1){
			$userinfo['teamyeji'] = round($teamyeji,2);
		}
        $rdata['teamnum_show'] = $set['teamnum_show'];
		if($rdata['teamnum_show'] == 1){
			$userinfo['teamnum'] = $teamnum;
		}
        $rdata['gongxianfenhong_show'] = $gongxianfenhong_show;
		if($rdata['gongxianfenhong_show']==1){
			$userinfo['gongxianfenhong'] = round($gongxianfenhong,2);
			$userinfo['gongxianfenhong_txt'] = $set['gongxianfenhong_txt'];
		}
		$rdata['userinfo'] = $userinfo;
		return $this->json($rdata);
	}
	//佣金转余额
	public function commission2money(){
        try{
            Db::startTrans();
            $post = input('post.');
            $set = Db::name('admin_set')->where('aid',aid)->find();
            if($set['commission2money'] !=1){
                return $this->json(['status'=>0,'msg'=>'该功能未启用']);
            }
            $money = floatval($post['money']);
            $member = Db::name('member')->where('aid',aid)->where('id',mid)->lock(true)->find();
            if($money <= 0 || $money > $member['commission']){
                return $this->json(['status'=>0,'msg'=>'转入金额不正确']);
            }

            \app\common\Member::addcommission(aid,mid,0,-$money,t('佣金').'转'.t('余额'));
            \app\common\Member::addmoney(aid,mid,$money,t('佣金').'转'.t('余额'));
            Db::commit();
        }catch(Exception $e){
            Db::rollback();
        }
		
		return $this->json(['status'=>1,'msg'=>'转入成功']);
	}
	//佣金明细
	public function commissionlog(){
		$st = input('param.st');
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		if(input('param.keyword')) $where[] = ['remark', 'like', '%'.input('param.keyword').'%'];
		$pernum = 20;
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		if($st ==1){//提现记录
			$datalist = Db::name('member_commission_withdrawlog')->field("id,money,txmoney,`status`,from_unixtime(createtime)createtime")->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
		}else{ //佣金明细
			$datalist = Db::name('member_commissionlog')->field("id,commission money,`after`,from_unixtime(createtime)createtime,remark")->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
		}
		if(!$datalist) $datalist = [];
		return $this->json(['status'=>1,'data'=>$datalist]);
	}
	
	//佣金记录
    public function commissionrecord(){
		$pernum = 20;
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;

		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		$st = input('param.st');
		if($st == 0){
			$where[] = ['status','in','0,1'];
		}elseif($st == 1){
			$where[] = ['status','=',1];
		}elseif($st == 2){
			$where[] = ['status','=',0];
		}

		$datalist = Db::name('member_commission_record')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
		if(!$datalist) $datalist = [];
		foreach($datalist as $k=>$v){
			if($v['type'] == 'levelup'){
				$datalist[$k]['orderstatus'] = 1;
			}else{
				$datalist[$k]['orderstatus'] = Db::name($v['type'].'_order')->where('id',$v['orderid'])->value('status');
			}
			if($v['frommid']){
				$frommember = Db::name('member')->where('id',$v['frommid'])->find();
				if($frommember){
					$datalist[$k]['fromheadimg'] = $frommember['headimg'];
					$datalist[$k]['fromnickname'] = $frommember['nickname'];
				}else{
					$datalist[$k]['fromheadimg'] = '';
					$datalist[$k]['fromnickname'] = '';
				}
			}
		}
		return $this->json(['status'=>1,'data'=>$datalist]);
    }
	//佣金提现
	public function commissionWithdraw(){
		$set = Db::name('admin_set')->where('aid',aid)->field('withdraw_autotransfer,comwithdraw,comwithdrawmin,comwithdrawfee,comwithdrawbl,comwithdrawdate,withdraw_weixin,withdraw_aliaccount,withdraw_bankcard')->find();
		if(request()->isPost()){
			$post = input('post.');
			if($set['comwithdraw'] == 0){
				return $this->json(['status'=>0,'msg'=>t('佣金').'提现功能未开启']);
			}
			$memberlevel = Db::name('member_level')->where('id',$this->member['levelid'])->find();
			if($memberlevel['comwithdraw'] == 0){
				return $this->json(['status'=>0,'msg'=>t('佣金').'提现功能未开启']);
			}

			if($post['paytype']=='支付宝' && $this->member['aliaccount']==''){
				return $this->json(['status'=>0,'msg'=>'请先设置支付宝账号']);
			}
			if($post['paytype']=='银行卡' && ($this->member['bankname']==''||$this->member['bankcarduser']==''||$this->member['bankcardnum']=='')){
				return $this->json(['status'=>0,'msg'=>'请先设置完整银行卡信息']);
			}

			$money = $post['money'];
			if($money<=0 || $money < $set['comwithdrawmin']){
				return $this->json(['status'=>0,'msg'=>'提现金额必须大于'.($set['comwithdrawmin']?$set['comwithdrawmin']:0)]);
			}
			if($money > $this->member['commission']){
				return $this->json(['status'=>0,'msg'=>'可提现'.t('余额').'不足']);
			}
			
			$ordernum = date('ymdHis').aid.rand(1000,9999);
			$record['aid'] = aid;
			$record['mid'] = mid;
			$record['createtime']= time();
			$record['money'] = $money*(1-$set['comwithdrawfee']*0.01);
			$record['txmoney'] = $money;
			if($post['paytype']=='支付宝'){
				$record['aliaccountname'] = $this->member['aliaccountname'];
				$record['aliaccount'] = $this->member['aliaccount'];
			}
			if($post['paytype']=='银行卡'){
				$record['bankname'] = $this->member['bankname'].($this->member['bankaddress'] ? ' '.$this->member['bankaddress'] : '');;
				$record['bankcarduser'] = $this->member['bankcarduser'];
				$record['bankcardnum'] = $this->member['bankcardnum'];
			}
			$record['ordernum'] = $ordernum;
			$record['paytype'] = $post['paytype'];
			$record['platform'] = platform;
			$recordid = Db::name('member_commission_withdrawlog')->insertGetId($record);

			\app\common\Member::addcommission(aid,mid,0,-$money,t('佣金').'提现');
			
			$tmplcontent = array();
			$tmplcontent['first'] = '有客户申请'.t('佣金').'提现';
			$tmplcontent['remark'] = '点击进入查看~';
			$tmplcontent['keyword1'] = $this->member['nickname'];
			$tmplcontent['keyword2'] = date('Y-m-d H:i');
			$tmplcontent['keyword3'] = $money.'元';
			$tmplcontent['keyword4'] = $post['paytype'];
			\app\common\Wechat::sendhttmpl(aid,0,'tmpl_withdraw',$tmplcontent,m_url('admin/finance/comwithdrawlog'));

			$tmplcontent = [];
			$tmplcontent['name3'] = $this->member['nickname'];
			$tmplcontent['amount1'] = $money.'元';
			$tmplcontent['date2'] = date('Y-m-d H:i');
			$tmplcontent['thing4'] = '提现到'.$post['paytype'];
			\app\common\Wechat::sendhtwxtmpl(aid,0,'tmpl_withdraw',$tmplcontent,'admin/finance/comwithdrawlog');

			if($set['withdraw_autotransfer']){
				if($set['comwithdrawbl'] > 0 && $set['comwithdrawbl'] < 100){
					$paymoney = round($record['money'] * $set['comwithdrawbl'] * 0.01,2);
					$tomoney = round($record['money'] - $paymoney,2);
				}else{
					$paymoney = $record['money'];
					$tomoney = 0;
				}
				$rs = \app\common\Wxpay::transfers(aid,mid,$paymoney,$record['ordernum'],platform,t('佣金').'提现');
				if($rs['status']==0){
					return json(['status'=>1,'msg'=>'提交成功,请等待打款']);
				}else{
					if($tomoney > 0){
						\app\common\Member::addmoney(aid,mid,$tomoney,t('佣金').'提现');
					}
					Db::name('member_commission_withdrawlog')->where('aid',aid)->where('id',$recordid)->update(['status'=>3,'paytime'=>time(),'paynum'=>$rs['resp']['payment_no']]);
					//提现成功通知
					$tmplcontent = [];
					$tmplcontent['first'] = '您的提现申请已打款，请留意查收';
					$tmplcontent['remark'] = '请点击查看详情~';
					$tmplcontent['money'] = (string) round($record['money'],2);
					$tmplcontent['timet'] = date('Y-m-d H:i',$record['createtime']);
					\app\common\Wechat::sendtmpl(aid,$record['mid'],'tmpl_tixiansuccess',$tmplcontent,m_url('pages/my/usercenter'));
					//订阅消息
					$tmplcontent = [];
					$tmplcontent['amount1'] = $record['money'];
					$tmplcontent['thing3'] = '微信打款';
					$tmplcontent['time5'] = date('Y-m-d H:i');
					
					$tmplcontentnew = [];
					$tmplcontentnew['amount3'] = $record['money'];
					$tmplcontentnew['phrase9'] = '微信打款';
					$tmplcontentnew['date8'] = date('Y-m-d H:i');
					\app\common\Wechat::sendwxtmpl(aid,$record['mid'],'tmpl_tixiansuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);
					//短信通知
					if($this->member['tel']){
						\app\common\Sms::send(aid,$this->member['tel'],'tmpl_tixiansuccess',['money'=>$record['money']]);
					}
					return json(['status'=>1,'msg'=>$rs['msg']]);
				}
			}
			return $this->json(['status'=>1,'msg'=>'提交成功,请等待打款']);
		}
		if($set['comwithdraw'] == 0){
			return $this->json(['status'=>-4,'msg'=>t('佣金').'提现功能未开启']);
		}
		$memberlevel = Db::name('member_level')->where('id',$this->member['levelid'])->find();
		if($memberlevel['comwithdraw'] == 0){
			return $this->json(['status'=>-4,'msg'=>t('佣金').'提现未开启','url'=>'/activity/commission/index']);
		}
		//订阅消息
		$wx_tmplset = Db::name('wx_tmplset')->where('aid',aid)->find();
		$tmplids = [];
		if($wx_tmplset['tmpl_tixiansuccess_new']){
			$tmplids[] = $wx_tmplset['tmpl_tixiansuccess_new'];
		}elseif($wx_tmplset['tmpl_tixiansuccess']){
			$tmplids[] = $wx_tmplset['tmpl_tixiansuccess'];
		}
		if($wx_tmplset['tmpl_tixianerror_new']){
			$tmplids[] = $wx_tmplset['tmpl_tixianerror_new'];
		}elseif($wx_tmplset['tmpl_tixianerror']){
			$tmplids[] = $wx_tmplset['tmpl_tixianerror'];
		}
		$rdata = [];
		$rdata['userinfo'] = Db::name('member')->where('id',mid)->field('id,headimg,nickname,money,score,commission,aliaccount,bankname,bankcarduser,bankcardnum')->find();
		$rdata['sysset'] = $set;
		$rdata['tmplids'] = $tmplids;
		return $this->json($rdata);
	}
	//我的团队
	public function team(){
		
		$userinfo = Db::name('member')->field('id,nickname,headimg,levelid')->where('aid',aid)->where('id',mid)->find();
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$userinfo['levelid'])->find();

		$downdeep = input('param.st/d');
		$pernum = 20;
		$pagenum = input('post.pagenum');
		$keyword = input('post.keyword');
		$where2 = "1=1";
		if($keyword) $where2 = "(nickname like '%{$keyword}%' or realname like '%{$keyword}%' or tel like '%{$keyword}%')";
		if(!$pagenum) $pagenum = 1;
		if(!$downdeep) $downdeep = 1;
		if(!mid){
			$datalist = [];
		}else{
			if($downdeep == 1){
				$datalist = Db::name('member')->field("id,nickname,headimg,tel,totalcommission,from_unixtime(createtime)createtime,levelid")->where("aid=".aid." and pid=".mid."")->where($where2)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			}elseif($downdeep == 2){
				$datalist = Db::query("select id,nickname,headimg,tel,totalcommission,from_unixtime(createtime)createtime,levelid from ".table_name('member')." where aid=".aid." and $where2 and pid in(select id from ".table_name('member')." where pid=".mid.") order by id desc limit ".($pagenum*$pernum-$pernum).','.$pernum);
			}elseif($downdeep == 3){
				$datalist = Db::query("select id,nickname,headimg,tel,totalcommission,from_unixtime(createtime)createtime,levelid from ".table_name('member')." where aid=".aid." and pid in(select id from ".table_name('member')." where aid=".aid." and $where2 and pid in(select id from ".table_name('member')." where pid=".mid.")) order by id desc limit ".($pagenum*$pernum-$pernum).','.$pernum);
			}
		}
		if(!$datalist) $datalist = [];
		foreach($datalist as $k=>$v){
			//if($downdeep==1){
			//	$commission = Db::name('shop_order_goods')->where('aid',aid)->where('mid',$v['id'])->where('parent1',mid)->where('status',3)->sum('parent1commission');
			//}
			//if($downdeep==2){
			//	$commission = Db::name('shop_order_goods')->where('aid',aid)->where('mid',$v['id'])->where('parent2',mid)->where('status',3)->sum('parent2commission');
			//}
			//if($downdeep==3){
			//	$commission = Db::name('shop_order_goods')->where('aid',aid)->where('mid',$v['id'])->where('parent3',mid)->where('status',3)->sum('parent3commission');
			//}

			$commission = Db::name('member_commission_record')->where('aid',aid)->where('mid',mid)->where('frommid',$v['id'])->where('status',1)->sum('commission');

			$datalist[$k]['commission'] = 0 + $commission;
			$datalist[$k]['downcount'] = 0 + Db::name('member')->where('aid',aid)->where('pid',$v['id'])->count();
			$level = Db::name('member_level')->where('aid',aid)->where('id',$v['levelid'])->find();
            $datalist[$k]['levelname'] = $level['name'];
            $datalist[$k]['levelsort'] = $level['sort'];
			if($userlevel['team_showtel'] == 0){
				$datalist[$k]['tel'] = '';
			}
		}
		if($pagenum == 1){
			//我的团队
			$userinfo['myteamCount1'] = 0 + Db::name('member')->where("aid=".aid." and pid=".mid)->count();
			$myteamCount2 = Db::query("select count(1)c from ".table_name('member')." where aid=".aid." and pid in(select id from ".table_name('member')." where pid=".mid.")");
			$userinfo['myteamCount2'] = 0 + $myteamCount2[0]['c'];
			$myteamCount3 = Db::query("select count(1)c from ".table_name('member')." where aid=".aid." and pid in(select id from ".table_name('member')." where aid=".aid." and pid in(select id from ".table_name('member')." where pid=".mid."))");
			$userinfo['myteamCount3'] = 0 + $myteamCount3[0]['c'];
			$userinfo['myteamCount'] = $userinfo['myteamCount1'] + $userinfo['myteamCount2'];
			//分销订单
			$userinfo['fxorderCount'] = 0 + Db::name("shop_order_goods")->where("aid=".aid." and (parent1=".mid." or parent2=".mid." or parent3=".mid.")")->count();
            $levelList = Db::name('member_level')->field('id,sort,name')->where('aid',aid)->where('id', 'in', explode(',',$userlevel['team_levelup_id']))->order('sort', 'asc')->select();
            $newKey = 'id';
            $levelList = $levelList->dictionary(null, $newKey);
		}
		$rdata = [];
		$rdata['datalist'] = $datalist;
		$rdata['userinfo'] = $userinfo;
		$rdata['userlevel'] = $userlevel;
		$rdata['levelList'] = $levelList;
		$rdata['st'] = $downdeep;
		return $this->json($rdata);
	}
	//分销订单
	public function agorder(){
		//拼团的佣金订单
		$pernum = 20;
		$pagenum = input('param.pagenum') ? input('param.pagenum') :1;
		$where = '';
		$st = input('param.st/d');
		if(!$st) $st = 0;
		if($st==1){//待付款
			$where = " and o.status=0";
		}
		if($st==2){//已付款
			$where = " and (o.status=1 or o.status=2)";
		}
		if($st==3){//已完成
			$where = " and o.status=3";
		}
		if($st==5){//售后
			$where = " and o.refund_money>0";
		}
		$datalist = Db::query("select og.id,og.mid,o.ordernum,o.status,o.createtime,o.paytime,og.name,og.proid,og.pic,og.num,og.parent1,og.parent2,og.parent3,og.parent1commission,og.parent2commission,og.parent3commission,og.parent1score,og.parent2score,og.parent3score from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." $where and  (og.parent1=".mid." or og.parent2=".mid." or og.parent3=".mid.") order by og.id desc limit ".($pagenum*$pernum-$pernum).','.$pernum);
		if(!$datalist) $datalist = [];
		$newdatalist = [];
		foreach($datalist as $k=>$v){
			$data = [];
			$data['ordernum'] = $v['ordernum'];
			$data['name'] = $v['name'];
			$data['pic'] = $v['pic'];
			$data['num'] = $v['num'];
			$data['createtime'] = date('Y-m-d H:i',$v['createtime']);
			$data['status'] = $v['status'];
			$memberinfo = Db::name('member')->where('id',$v['mid'])->field('nickname,headimg')->find();
			$data['nickname'] = $memberinfo['nickname'];
			$data['headimg'] = $memberinfo['headimg'];

			if($v['parent1'] == mid){
				$data['dengji'] = '一级';
				if($v['parent1score'] > 0){
					$data['commission'] = $v['parent1score'].t('积分');
				}else{
					$data['commission'] = $v['parent1commission'].'元';
				}
				$data['dannum'] = 0;
				}
			if($v['parent2'] == mid){
				$data['dengji'] = '二级';
				if($v['parent2score'] > 0){
					$data['commission'] = $v['parent2score'].t('积分');
				}else{
					$data['commission'] = $v['parent2commission'].'元';
				}
				$data['dannum'] = 0;
				}
			if($v['parent3'] == mid){
				$data['dengji'] = '三级';
				if($v['parent3score'] > 0){
					$data['commission'] = $v['parent3score'].t('积分');
				}else{
					$data['commission'] = $v['parent3commission'].'元';
				}
				$data['dannum'] = 0;
				}
			if(false){}else{
				$data['order_info'] = false;
			}
			$newdatalist[] = $data;
		}
		if(request()->isPost()){
			return $this->json(['data'=>$newdatalist]);
		}

		$count = Db::query("select count(1)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (og.parent1=".mid." or og.parent2=".mid." or og.parent3=".mid.")");
		$count = 0 + $count[0]['c'];

		$count1 = Db::query("select count(1)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and o.status=0 and (og.parent1=".mid." or og.parent2=".mid." or og.parent3=".mid.")");
		$count1 = 0 + $count1[0]['c'];

		$count2 = Db::query("select count(1)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2) and (og.parent1=".mid." or og.parent2=".mid." or og.parent3=".mid.")");
		$count2 = 0 + $count2[0]['c'];

		$count3 = Db::query("select count(1)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and o.status=3 and (og.parent1=".mid." or og.parent2=".mid." or og.parent3=".mid.")");
		$count3 = 0 + $count3[0]['c'];

		$commissionyj1 = Db::query("select sum(parent1commission)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2) and og.parent1=".mid."");
		$commissionyj2 = Db::query("select sum(parent2commission)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2) and og.parent2=".mid."");
		$commissionyj3 = Db::query("select sum(parent3commission)c from ".table_name('shop_order_goods')." og left join ".table_name('shop_order')." o on o.id=og.orderid where og.aid=".aid." and (o.status=1 or o.status=2) and og.parent3=".mid."");

		$commissionyj = 0 + $commissionyj1[0]['c'] + $commissionyj2[0]['c'] + $commissionyj3[0]['c'];
		
		$rdata = [];
		$rdata['count'] = $count;
		$rdata['count1'] = $count1;
		$rdata['count2'] = $count2;
		$rdata['count3'] = $count3;
		$rdata['commissionyj'] = round($commissionyj,2);
		$rdata['datalist'] = $newdatalist;
		$rdata['st'] = $st;
		return $this->json($rdata);
	}

	//股东分红
	public function fenhong(){
		$pernum = 20;
		$pagenum = input('param.pagenum') ? input('param.pagenum') :1;
		$where = '';
		$st = input('param.st/d');
		if(!$st) $st = 1;

		//待结算
		$newoglist = [];
		if($st == 1){
			$rs = \app\common\Fenhong::gdfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$newoglist = $rs['oglist'];
			$commissionyj = $rs['commissionyj'];
		}

		if($st==2){//已结算
			$where = [];
			$where[] = ['aid','=',aid];
			$where[] = ['mid','=',mid];
			$where[] = ['type','=','fenhong'];
			$pernum = 20;
			$pagenum = input('param.pagenum');
			if(!$pagenum) $pagenum = 1;
			$count = Db::name('member_fenhonglog')->where($where)->count();
			$datalist = Db::name('member_fenhonglog')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$datalist) $datalist = [];
			foreach($datalist as $k=>$v){
				if($v['ogids']){
					if($v['module'] == 'yuyue'){
						$oglist = Db::name('yuyue_order')->alias('og')->join('member m','og.mid=m.id')->field('og.ordernum,og.proname name,og.propic pic,og.num,og.totalprice real_totalprice,og.createtime,og.status,m.nickname,m.headimg')->where('og.id','in',$v['ogids'])->select()->toArray();
					}else{
						$oglist = Db::name('shop_order_goods')->alias('og')->join('member m','og.mid=m.id')->field('og.ordernum,og.name,og.pic,og.num,og.real_totalprice,og.createtime,og.status,m.nickname,m.headimg')->where('og.id','in',$v['ogids'])->select()->toArray();
					}
				}else{
					$oglist = [];
				}
				$datalist[$k]['oglist'] = $oglist;
			}
		}
		$rdata = [];
		$rdata['count'] = $count + count($newoglist);
		$rdata['commissionyj'] = round($commissionyj,2);
		if($st == 1){
			$rdata['datalist'] = $newoglist;
		}else{
			$rdata['datalist'] = $datalist;
		}
		$rdata['st'] = $st;
		return $this->json($rdata);
	}
	//团队分红
	public function teamfenhong(){
		$pernum = 20;
		$pagenum = input('param.pagenum') ? input('param.pagenum') :1;
		$where = '';
		$st = input('param.st/d');
		if(!$st) $st = 1;

		//待结算
		$newoglist = [];
		if($st == 1){
			$rs1 = \app\common\Fenhong::teamfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$rs2 = \app\common\Fenhong::product_teamfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$rs3 = \app\common\Fenhong::level_teamfenhong(aid,$this->sysset,[],0,time(),1,mid);

			$newoglist = [];
			$commissionyj = 0;
			if($rs1 && $rs1['oglist']){
				$newoglist = array_merge($newoglist,$rs1['oglist']);
				$commissionyj += $rs1['commissionyj'];
			}
			if($rs2 && $rs2['oglist']){
				$newoglist = array_merge($newoglist,$rs2['oglist']);
				$commissionyj += $rs2['commissionyj'];
			}
			if($rs3 && $rs3['oglist']){
				$newoglist = array_merge($newoglist,$rs3['oglist']);
				$commissionyj += $rs3['commissionyj'];
			}
		}

		if($st==2){//已结算
			$where = [];
			$where[] = ['aid','=',aid];
			$where[] = ['mid','=',mid];
			$where[] = ['type','=','teamfenhong'];
			$pernum = 20;
			$pagenum = input('param.pagenum');
			if(!$pagenum) $pagenum = 1;
			$count = Db::name('member_fenhonglog')->where($where)->count();
			$datalist = Db::name('member_fenhonglog')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$datalist) $datalist = [];
			foreach($datalist as $k=>$v){
				if($v['ogids']){
					if($v['module'] == 'yuyue'){
						$oglist = Db::name('yuyue_order')->alias('og')->join('member m','og.mid=m.id')->field('og.ordernum,og.proname name,og.propic pic,og.num,og.totalprice real_totalprice,og.createtime,og.status,m.nickname,m.headimg')->where('og.id','in',$v['ogids'])->select()->toArray();
					}else{
						$oglist = Db::name('shop_order_goods')->alias('og')->join('member m','og.mid=m.id')->field('og.ordernum,og.name,og.pic,og.num,og.real_totalprice,og.createtime,og.status,m.nickname,m.headimg')->where('og.id','in',$v['ogids'])->select()->toArray();
					}
				}else{
					$oglist = [];
				}
				$datalist[$k]['oglist'] = $oglist;
			}
		}
		$rdata = [];
		$rdata['count'] = $count + count($newoglist);
		$rdata['commissionyj'] = round($commissionyj,2);
		if($st == 1){
			$rdata['datalist'] = $newoglist;
		}else{
			$rdata['datalist'] = $datalist;
		}
		$rdata['st'] = $st;
		return $this->json($rdata);
	}
	//区域代理分红
	public function areafenhong(){
		$pernum = 20;
		$pagenum = input('param.pagenum') ? input('param.pagenum') :1;
		$where = '';
		$st = input('param.st/d');
		if(!$st) $st = 1;

		//待结算
		$newoglist = [];
		if($st == 1){
			$rs = \app\common\Fenhong::areafenhong(aid,$this->sysset,[],0,time(),1,mid);
			$newoglist = $rs['oglist'];
			$commissionyj = $rs['commissionyj'];
		}

		if($st==2){//已结算
			$where = [];
			$where[] = ['aid','=',aid];
			$where[] = ['mid','=',mid];
			$where[] = ['type','=','areafenhong'];
			$pernum = 20;
			$pagenum = input('param.pagenum');
			if(!$pagenum) $pagenum = 1;
			$count = Db::name('member_fenhonglog')->where($where)->count();
			$datalist = Db::name('member_fenhonglog')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$datalist) $datalist = [];
			foreach($datalist as $k=>$v){
				if($v['ogids']){
					if($v['module'] == 'yuyue'){
						$oglist = Db::name('yuyue_order')->alias('og')->join('member m','og.mid=m.id')->field('og.ordernum,og.proname name,og.propic pic,og.num,og.totalprice real_totalprice,og.createtime,og.status,m.nickname,m.headimg')->where('og.id','in',$v['ogids'])->select()->toArray();
					}else{
						$oglist = Db::name('shop_order_goods')->alias('og')->join('member m','og.mid=m.id')->field('og.ordernum,og.name,og.pic,og.num,og.real_totalprice,og.createtime,og.status,m.nickname,m.headimg')->where('og.id','in',$v['ogids'])->select()->toArray();
					}
				}else{
					$oglist = [];
				}
				$datalist[$k]['oglist'] = $oglist;
			}
		}
		$rdata = [];
		$rdata['count'] = $count + count($newoglist);
		$rdata['commissionyj'] = round($commissionyj,2);
		if($st == 1){
			$rdata['datalist'] = $newoglist;
		}else{
			$rdata['datalist'] = $datalist;
		}
		$rdata['st'] = $st;
		return $this->json($rdata);
	}

	//分红订单
	public function fhorder(){
		$pernum = 20;
		$pagenum = input('param.pagenum') ? input('param.pagenum') :1;
		$where = '';
		$st = input('param.st/d');
		if(!$st) $st = 1;

		$fhjiesuanbusiness = $this->sysset['fhjiesuanbusiness'];
        $fhjiesuantype = $this->sysset['fhjiesuantype'];
		$fhjiesuantime_type = $this->sysset['fhjiesuantime_type'];

		//待结算
		$newoglist = [];
		if($st == 1){
			$rs1 = \app\common\Fenhong::gdfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$rs2 = \app\common\Fenhong::teamfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$rs3 = \app\common\Fenhong::product_teamfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$rs4 = \app\common\Fenhong::level_teamfenhong(aid,$this->sysset,[],0,time(),1,mid);
			$rs5 = \app\common\Fenhong::areafenhong(aid,$this->sysset,[],0,time(),1,mid);

			$newoglist = [];
			$commissionyj = 0;
			if($rs1 && $rs1['oglist']){
				$newoglist = array_merge($newoglist,$rs1['oglist']);
				$commissionyj += $rs1['commissionyj'];
			}
			if($rs2 && $rs2['oglist']){
				$newoglist = array_merge($newoglist,$rs2['oglist']);
				$commissionyj += $rs2['commissionyj'];
			}
			if($rs3 && $rs3['oglist']){
				$newoglist = array_merge($newoglist,$rs3['oglist']);
				$commissionyj += $rs3['commissionyj'];
			}
			if($rs4 && $rs4['oglist']){
				$newoglist = array_merge($newoglist,$rs4['oglist']);
				$commissionyj += $rs4['commissionyj'];
			}
			if($rs5 && $rs5['oglist']){
				$newoglist = array_merge($newoglist,$rs5['oglist']);
				$commissionyj += $rs5['commissionyj'];
			}
		}

		if($st==2){//已结算
			$where = [];
			$where[] = ['aid','=',aid];
			$where[] = ['mid','=',mid];
			$pernum = 20;
			$pagenum = input('param.pagenum');
			if(!$pagenum) $pagenum = 1;
			$count = Db::name('member_fenhonglog')->where($where)->count();
			$datalist = Db::name('member_fenhonglog')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$datalist) $datalist = [];
			foreach($datalist as $k=>$v){
				if($v['ogids']){
					if($v['module'] == 'yuyue'){
						$oglist = Db::name('yuyue_order')->alias('og')->join('member m','og.mid=m.id')->field('og.ordernum,og.proname name,og.propic pic,og.num,og.totalprice real_totalprice,og.createtime,og.status,m.nickname,m.headimg')->where('og.id','in',$v['ogids'])->select()->toArray();
					}else{
						$oglist = Db::name('shop_order_goods')->alias('og')->join('member m','og.mid=m.id')->field('og.ordernum,og.name,og.pic,og.num,og.real_totalprice,og.createtime,og.status,m.nickname,m.headimg')->where('og.id','in',$v['ogids'])->select()->toArray();
					}
				}else{
					$oglist = [];
				}
				$datalist[$k]['oglist'] = $oglist;
			}
		}
		$rdata = [];
		$rdata['count'] = $count + count($newoglist);
		$rdata['commissionyj'] = round($commissionyj,2);
		if($st == 1){
			$rdata['datalist'] = $newoglist;
		}else{
			$rdata['datalist'] = $datalist;
		}
		$rdata['st'] = $st;
		return $this->json($rdata);
	}


    //门店服务订单
    public function orderMendian(){
        return $this->json([]);
    }
	
	//分红记录
	public function fhlog(){
		$st = input('param.st');
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		$pernum = 20;
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		$datalist = Db::name('member_fenhonglog')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
		if(!$datalist) $datalist = [];
		return $this->json(['status'=>1,'data'=>$datalist]);
	}
	//分享海报
	public function poster(){
		$member = $this->member;
		$platform = platform;
		$page = $this->indexurl;
		$scene = 'pid_'.$this->member['id'];
		//if($platform == 'mp' || $platform == 'h5' || $platform == 'app'){
		//	$page = PRE_URL .'/h5/'.aid.'.html#'. $page;
		//}

		if(input('param.posterid')){
			$posterset = Db::name('admin_set_poster')->where('aid',aid)->where('type','index')->where('platform',$platform)->where('id',input('param.posterid'))->find();
		}else{
			$posterset = Db::name('admin_set_poster')->where('aid',aid)->where('type','index')->where('platform',$platform)->order('id')->find();
		}
		$posterdata = Db::name('member_poster')->where('aid',aid)->where(['mid'=>mid,'posterid'=>$posterset['id']])->find();
		$sysset = Db::name('admin_set')->field('id,name,logo,desc')->where('aid',aid)->find();
		if(!$posterdata){
			$textReplaceArr = [
				'[头像]'=>$member['headimg'],
				'[昵称]'=>$member['nickname'],
				'[姓名]'=>$member['realname'],
				'[手机号]'=>$member['tel'],
				'[商城名称]'=>$sysset['name'],
			];
			$poster = $this->_getposter(aid,$platform,$posterset['content'],$page,$scene,$textReplaceArr);
			$posterdata = [];
			$posterdata['aid'] = aid;
			$posterdata['mid'] = $member['id'];
			$posterdata['scene'] = $scene;
			$posterdata['page'] = $page;
			$posterdata['poster'] = $poster;
			$posterdata['posterid'] = $posterset['id'];
			$posterdata['createtime'] = time();
			Db::name('member_poster')->insert($posterdata);
		}

		$posterlist = Db::name('admin_set_poster')->field('id')->where('aid',aid)->where('type','index')->where('platform',$platform)->order('id')->select()->toArray();

		$rdata = [];
		$rdata['poster'] = $posterdata['poster'];
		$rdata['guize'] = $posterset['guize'];
		$rdata['posterid'] = $posterset['id'];
		$rdata['posterlist'] = $posterlist;
		$rdata['postercount'] = count($posterlist);
		return $this->json($rdata);
	}
	//给余额
	public function givemoney(){
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();
		if($userlevel['team_givemoney'] == 0) return $this->json(['status'=>0,'msg'=>'给下级转账功能未开启']);
		$id = input('param.id/d');
		$money = input('param.money/f');
		if($money <= 0) return $this->json(['status'=>0,'msg'=>'转账金额必须大于0']);
		$tomember = Db::name('member')->where('aid',aid)->where('id',$id)->find();
		if(!$tomember) return $this->json(['status'=>0,'msg'=>'用户不存在']);
		if($money > $this->member['money']) return $this->json(['status'=>0,'msg'=>t('余额').'不足']);
		\app\common\Member::addmoney(aid,$id,$money,$this->member['nickname'].'-转账');
		\app\common\Member::addmoney(aid,mid,-$money,'转账给'.$tomember['nickname']);
		return $this->json(['status'=>1,'msg'=>'转账成功']);
	}
	//给积分
	public function givescore(){
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();
		if($userlevel['team_givescore'] == 0) return $this->json(['status'=>0,'msg'=>'给下级转账功能未开启']);
		$id = input('param.id/d');
		$score = input('param.score/d');
		if($score <= 0) return $this->json(['status'=>0,'msg'=>'转账数量必须大于0']);
		$tomember = Db::name('member')->where('aid',aid)->where('id',$id)->find();
		if(!$tomember) return $this->json(['status'=>0,'msg'=>'用户不存在']);
		if($score > $this->member['score']) return $this->json(['status'=>0,'msg'=>t('积分').'不足']);
		\app\common\Member::addscore(aid,$id,$score,$this->member['nickname'].'-转账');
		\app\common\Member::addscore(aid,mid,-$score,'转账给'.$tomember['nickname']);
		return $this->json(['status'=>1,'msg'=>'转账成功']);
	}

	//升级（分销商给下级升级
	public function levelUp()
    {
        if(!getcustom('plug_zhiming')) {
            return $this->json(['status'=>0,'msg'=>'操作失败']);
        }
        $mid = input('param.mid/d');
        $levelId = input('param.levelId/d');

        $tomember = Db::name('member')->where('aid',aid)->where('id',$mid)->find();
        if(!$tomember) return $this->json(['status'=>0,'msg'=>'用户不存在']);
        if(!in_array(mid,explode(',',$tomember['path']))) {
            return $this->json(['status'=>0,'msg'=>'无权限操作此用户']);
        }

        $memberlevel = Db::name('member_level')->where('aid',aid)->where('id',$tomember['levelid'])->find();
        $tolevel = Db::name('member_level')->where('aid',aid)->where('id',$levelId)->find();
        if($tolevel['sort'] <= $memberlevel['sort']) {
            return $this->json(['status'=>0,'msg'=>'只能为用户升级']);
        }

        $userlevel = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();
        if($userlevel['sort'] <= $tolevel['sort']) return $this->json(['status'=>0,'msg'=>'给下级升级需低于推广员当前等级']);
        if($userlevel['team_levelup'] == 0) return $this->json(['status'=>0,'msg'=>'给下级升级功能未开启']);
        if($userlevel['team_levelup_num'] <= 0) return $this->json(['status'=>0,'msg'=>'给下级升级数量不足']);

        $count = Db::name('member_levelup_order')->where('aid', aid)->where('from_mid', mid)->count();
        if($count >= $userlevel['team_levelup_num']) {
            return $this->json(['status'=>0,'msg'=>'给下级升级数量不足']);
        }

        $order = [
            'aid' => aid,
            'mid' => $mid,
            'from_mid' => mid,
            'levelid' => $levelId,
            'title' => '推广员为下级升级，推广员：'.$this->member['nickname'],
            'totalprice' => 0,
            'createtime' => time(),
            'beforelevelid' => $tomember['levelid'],
            'form0' => '类型^_^推广员为下级升级',
            'form1' => '推广员^_^'.$this->member['nickname'],
            'platform' => platform,
            'status' => 2
        ];
        Db::name('member_levelup_order')->insert($order);

        $newlv = Db::name('member_level')->where('aid',aid)->where('id',$levelId)->find();
        if($newlv['yxqdate'] > 0){
            $levelendtime = strtotime(date('Y-m-d')) + 86400 + 86400 * $newlv['yxqdate'];
        }else{
            $levelendtime = 0;
        }
        Db::name('member')->where('id',$mid)->update(['levelid'=>$newlv['id'],'levelstarttime'=>time(),'levelendtime'=>$levelendtime]);

        \app\common\Wechat::updatemembercard(aid,$mid);

        $tmplcontent = [];
        $tmplcontent['first'] = '恭喜您成功升级为'.$newlv['name'];
        $tmplcontent['remark'] = '点击进入查看~';
        $tmplcontent['keyword1'] = $newlv['name']; //会员等级
        $tmplcontent['keyword2'] = '已生效';//审核状态
        \app\common\Wechat::sendtmpl(aid,$mid,'tmpl_uplv',$tmplcontent,m_url('pages/my/usercenter'));

        return $this->json(['status'=>1,'msg'=>'升级成功']);
    }


    //佣金明细
    public function orderYeji(){
        $st = input('param.st');
        $level = Db::name('member_level')->where('id', $this->member['levelid'])->find();
        if(empty($level['tongji_yeji']) || $level['tongji_yeji'] != 1) {
            $datalist = [];
            return $this->json(['status'=>1,'data'=>$datalist]);
        }
        $pernum = 15;
        $pagenum = input('post.pagenum');
        if(!$pagenum) $pagenum = 1;
        $childrenmids = \app\common\Member::getdownmids(aid,mid);
        $childrenmids[] = mid;
        $date = strtotime(date('Y-m-d'));

        for ($i=($pagenum-1)*$pernum;$i<$pagenum*$pernum;$i++) {
            $start = $date-$i*86400;
            $end = $start + 86399;
            $where = [];
            $where[] = ['aid','=',aid];
            $where[] = ['mid','in',$childrenmids];
            $where[] = ['status','in',[1,2,3]];
            $where[] = ['createtime','between',[$start,$end]];
            $num = Db::name('shop_order_goods')->where($where)->sum('num');
            $datalist[] = [
                'i'=>$i,
                'date' => date('Y-m-d',$start),
                'num' => $num
            ];
        }

        if(!$datalist) $datalist = [];
        return $this->json(['status'=>1,'data'=>$datalist]);
    }


	//我的上下级
	public function teamline(){
		
		$userinfo = Db::name('member')->field('id,nickname,headimg,levelid,path')->where('aid',aid)->where('id',mid)->find();
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$userinfo['levelid'])->find();

		$pernum = 20;
		$pagenum = input('post.pagenum');
		$keyword = input('post.keyword');
		$where2 = "1=1";
		if($keyword) $where2 = "(nickname like '%{$keyword}%' or realname like '%{$keyword}%' or tel like '%{$keyword}%')";
		if(!$pagenum) $pagenum = 1;
		if(!mid){
			$datalist = [];
		}else{
			$datalist = Db::name('member')->where('aid',aid)->where('find_in_set('.mid.',path)'.($userinfo['path'] ? ' or id in ('.$userinfo['path'].')' : ''))->where($where2)->order('id')->page($pagenum,$pernum)->select()->toArray();
			//echo Db::getlastsql();
		}

		foreach($datalist as $k=>$v){
			$level = Db::name('member_level')->where('aid',aid)->where('id',$v['levelid'])->find();
            $datalist[$k]['levelname'] = $level['name'];
            $datalist[$k]['levelsort'] = $level['sort'];
			if($userlevel['team_showtel'] == 0){
				$datalist[$k]['tel'] = '';
			}
		}
		
		$rdata = [];
		$rdata['datalist'] = $datalist;
		$rdata['userinfo'] = $userinfo;
		$rdata['userlevel'] = $userlevel;
		$rdata['st'] = $downdeep;
		return $this->json($rdata);
	}
	//我的同等级会员
	public function sameline(){
		$userinfo = Db::name('member')->field('id,nickname,headimg,levelid,path')->where('aid',aid)->where('id',mid)->find();
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$userinfo['levelid'])->find();

		$pernum = 20;
		$pagenum = input('post.pagenum');
		$keyword = input('post.keyword');
		$where2 = "1=1";
		if($keyword) $where2 = "(nickname like '%{$keyword}%' or realname like '%{$keyword}%' or tel like '%{$keyword}%')";
		if(!$pagenum) $pagenum = 1;
		if(!mid){
			$datalist = [];
		}else{
			$datalist = Db::name('member')->where('aid',aid)->where('levelid',$userinfo['levelid'])->where($where2)->order('id')->page($pagenum,$pernum)->select()->toArray();
			//echo Db::getlastsql();
		}

		foreach($datalist as $k=>$v){
			$level = Db::name('member_level')->where('aid',aid)->where('id',$v['levelid'])->find();
            $datalist[$k]['levelname'] = $level['name'];
            $datalist[$k]['levelsort'] = $level['sort'];
			if($userlevel['team_showtel'] == 0){
				$datalist[$k]['tel'] = '';
			}
		}
		
		$rdata = [];
		$rdata['datalist'] = $datalist;
		$rdata['userinfo'] = $userinfo;
		$rdata['userlevel'] = $userlevel;
		$rdata['st'] = $downdeep;
		return $this->json($rdata);
	}

	//佣金排行
	public function commissionrank(){
		$pernum = 20;
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;

		$where = [];
		$where[] = ['aid','=',aid];
		$datalist = Db::name('member')->where($where)->page($pagenum,$pernum)->order('totalcommission desc')->select()->toArray();
		if(!$datalist) $datalist = [];
		return $this->json(['status'=>1,'data'=>$datalist,'totalcommission'=>$this->member['totalcommission'],'commission'=>$this->member['commission']]);
    }


}